//app.js
App({
  debug: false,
  onLaunch: function () {
    Promise.prototype.finally = function (callback) {
      let P = this.constructor;
      return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason })
      );
    };
  },
  globalData: {
    //server:"p017.zhenlutech.com",
    url: "https://p020.zhenlutech.com/index.php/api/",
    key: "huge9e8293423f89n2sdfdwefwef"
  },
  //便捷的请求函数 可以自动登陆 应使用此函数访问接口
  request: function (api, params, needlogin) {
    return new Promise(function (resolve, reject) {
      if (typeof (params) != "object") {
        params = {}
      }
      resolve(params)
    }).then(function (data) {
      return new Promise(function (resolve, reject) {
        if (typeof (needlogin) == "boolean" && needlogin) {
          getApp().get_token().then(function (token) {
            data.token = token
            resolve(data)
          })
        } else {
          resolve(data)
        }
      })
    }).then(function (data) {
      return getApp().request_api(api, data);
    })
  },
  get_token: function () {//获取登陆会话
    return new Promise(function (resolve, reject) {
      var token = wx.getStorageSync("token")
      var expire = wx.getStorageSync("expire")
            
      //检测是否已登录
      if (token && Date.now() < expire && !getApp().debug)//会话存在且没有超时,无需登录
      {
        console.log("无需登录")
        resolve(token)

      } else {//需要登陆
        getApp().get_wx_login_code().then(function (code) {
          return getApp().request_api("get_token", { code: code })
        }).then(function (data) {
          if (data.code == 0) {
            var token = data.token;
            wx.setStorageSync("token", token)
            wx.setStorageSync("expire", Date.now() + 10 * 60 * 1000)

            //上传用户信息
            wx.getSetting({
              success(res) {
                if (!res.authSetting['scope.userInfo'] || getApp().debug) {
                  wx.authorize({
                    scope: 'scope.userInfo',
                    success() {
                      wx.getUserInfo({
                        success: function (res) {
                          var userInfo = res.userInfo
                          getApp().request("update_userinfo", res.userInfo, true);

                        }
                      })
                    }
                  })
                }
              }
            })

            resolve(token)
            console.log("登录成功")
          } else {
            reject("登陆失败：无效的code")
          }
        })
      }
    })
  },
  get_wx_login_code: function () {//获取微信登陆code
    return new Promise(function (resolve, reject) {
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            resolve(res.code)
          } else {
            reject("获取登陆态失败")
          }
        },
        fail: function (err) {
          reject("登陆失败")
        }
      })
    })
  },
  //基本请求函数,会自动附加API所需的APPKEY
  request_api: function (api, data) {
    console.log("excuting " + api, data)
    return new Promise(function (resolve, reject) {
      wx.request({
        url: getApp().globalData.url + api,
        data: data,
        header: {
          'Content-Type': 'application/json',
          'APIKEY': getApp().globalData.key
        },
        success: function (res) {
          console.log("result of " + api, res)
          resolve(res.data)
        },
        faild: function (err) {
          reject(err)
        }
      })
    })
  },
  test: function () {
    var basic_test = this.request("test")
    basic_test.then(function (data) {
      console.log(data.message)
      return
    })

    var login_test = this.request("test", {}, true)
    login_test.then(function (data) {
      console.log(data.message)
      return
    })
  }
})
